package com.cb.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.cb.activity.NetLocationManager.LocationCallBack;
//import com.cb.version.UpdateManager;
import com.cb.view.LButton;
import com.mapkit.yous.R;
import com.mapkit.ResourceProxy;
import com.mapkit.Wgtochina;
import com.mapkit.Wgtochina.LonLatDouble;
import com.mapkit.constants.CBMapConstants;
import com.mapkit.geocode.GeocodeService;
import com.mapkit.geocode.YSPOIData;
import com.mapkit.util.BoundingBoxE6;
import com.mapkit.util.GeoPoint;
import com.mapkit.util.ResourceProxyImpl;
import com.mapkit.views.MapView;
import com.mapkit.views.Projection;
import com.mapkit.views.overlay.ItemizedIconOverlay;
import com.mapkit.views.overlay.ItemizedOverlayWithFocus;
import com.mapkit.views.overlay.Overlay;
import com.mapkit.views.overlay.OverlayItem;
import com.mapkit.views.overlay.PathOverlay;

@SuppressWarnings("deprecation")
public class MainActivity extends Activity implements CBMapConstants,
		LocationCallBack {

	private SharedPreferences mPrefs;
	private ResourceProxy mResourceProxy;

	boolean isSatellite = false;
	LButton satelliteBtn = null;

	private MapView mMapView;

	public static final int ANDROID_BUILD_GINGERBREAD = 9;
	public static final int SCREEN_ORIENTATION_SENSOR_LANDSCAPE = 6;

	private NetLocationManager mNetLocation;

	@Override
	public void onCreate(final Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// if (Build.VERSION.SDK_INT >= ANDROID_BUILD_GINGERBREAD)
		// {
		// setRequestedOrientation(SCREEN_ORIENTATION_SENSOR_LANDSCAPE);
		// }
		NetLocationManager.init(this, MainActivity.this);// 初始化
		mNetLocation = NetLocationManager.getInstance();

		setContentView(R.layout.activity_main);
		mMapView = (MapView) findViewById(R.id.myOSMmapview);

		initMaps();

		/*
		 * isSatellite = true; if (isSatellite) { satelliteBtn.setText("卫星图");
		 * // 设置地图类型为卫星图 mMapView.setMapType(MapView.MAP_TYPE_SATELLITE); } else
		 * { satelliteBtn.setText("平面图"); // 设置地图类型为平面图
		 * mMapView.setMapType(MapView.MAP_TYPE_NORMAL); }
		 */

		// UpdateManager.getUpdateManager().checkAppUpdate(this, false);
		updatePG();

		mTimer = new Timer();
		mTimer.schedule(new TimerTask() {
			@Override
			public void run() {
				//_splash++;
				mHandler.sendEmptyMessage(777);
			}
		}, 1, 1000);
	}
	
	int _splash = 0;
	private Timer mTimer = null;
	private Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 777: {
				mMapView.postInvalidate();
			}
				break;
			default:
				break;
			}
		}
	};

	void initMaps() {
		mMapView.setMultiTouchControls(true);

		// 加入新图层
		mMapOverlay = new MapOverlay(this);
		mMapView.getOverlayManager().add(mMapOverlay);

		// 设置地图类型为平面图
		mMapView.setMapType(MapView.MAP_TYPE_NORMAL);

		// 初始化设置地图的比例尺和中心点
		mPrefs = getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
		int x = mPrefs.getInt(PREFS_SCROLL_X, 0);
		int y = mPrefs.getInt(PREFS_SCROLL_Y, 0);
		if (x > 0 && y > 0) {
			// 返回上次记录位置
			mMapView.getController()
					.setZoom(mPrefs.getInt(PREFS_ZOOM_LEVEL, 1));
			mMapView.scrollTo(x, y);
		} else {
			// 济宁公安局
			GeoPoint center = new GeoPoint(35.42143, 116.61295);
			mMapView.getController().setCenter(center);
			mMapView.getController().setZoom(14);
		}

		// 初始化车标位置
		_carll = mMapView.getMapCenter();
		// 初始化车标的方向
		_dir = 60;
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		super.onPause();
		final SharedPreferences.Editor edit = mPrefs.edit();
		edit.putString(PREFS_TILE_SOURCE, mMapView.getTileProvider()
				.getTileSource().name());
		edit.putInt(PREFS_SCROLL_X, mMapView.getScrollX());
		edit.putInt(PREFS_SCROLL_Y, mMapView.getScrollY());
		edit.putInt(PREFS_ZOOM_LEVEL, mMapView.getZoomLevel());
		edit.commit();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig); // 检测屏幕的方向：纵向或横向
		if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			// 当前为横屏， 在此处添加额外的处理代码
		} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
			// 当前为竖屏， 在此处添加额外的处理代码
		}
	}

	@Override
	public void finish() {
		// 保存地图的比例尺和中心点
		final SharedPreferences.Editor edit = mPrefs.edit();
		edit.putString(PREFS_TILE_SOURCE, mMapView.getTileProvider()
				.getTileSource().name());
		edit.putInt(PREFS_SCROLL_X, mMapView.getScrollX());
		edit.putInt(PREFS_SCROLL_Y, mMapView.getScrollY());
		edit.putInt(PREFS_ZOOM_LEVEL, mMapView.getZoomLevel());
		edit.commit();
		super.finish();
	}

	public void updatePG() {
		if (isSatellite) {
			findViewById(R.id.id_planmap).setVisibility(View.GONE);
			findViewById(R.id.id_satellitmap).setVisibility(View.VISIBLE);
		} else {
			findViewById(R.id.id_planmap).setVisibility(View.VISIBLE);
			findViewById(R.id.id_satellitmap).setVisibility(View.GONE);
		}
	}
	
	GeoPoint _center;

	public void onSatellite(View v) {
		GeoPoint center = mMapView.getMapCenter();
		mMapView.setMapType(MapView.MAP_TYPE_SATELLITE);
		mMapView.getController().setCenter(center);
		isSatellite = true;
		_center = center;
		updatePG();
	}

	public void onPlan(View v) {
		GeoPoint center = mMapView.getMapCenter();
		isSatellite = false;
		mMapView.setMapType(MapView.MAP_TYPE_NORMAL);
		mMapView.getController().setCenter(center);
		_center = center;
		updatePG();
	}

	public void onZoomin(View v) {
		mMapView.getController().zoomIn();
	}

	public void onZoomout(View v) {
		mMapView.getController().zoomOut();
	}

	public void onSearch(View v) {
		// Intent intent = new Intent(this, SearchActivity.class);
		// startActivityForResult(intent, 1);
		Intent intent = new Intent(this, SMainActivity.class);
		startActivityForResult(intent, 1);

	}

	public void onCenterLL(View v) {
		GeoPoint center = mMapView.getMapCenter();
		String name = "中心点的经纬度：\n" + (float) center.getLatitude() + " "
				+ (float) center.getLongitude();
		Toast.makeText(this, name, Toast.LENGTH_LONG).show();

		// 获取屏幕像素（dp）对应的经纬度－－－XY2LL
		final Projection pj = mMapView.getProjection();
		GeoPoint gp = (GeoPoint) pj.fromPixels(100, 88, null);

		// 获取经纬度对应的屏幕像素---LL2XY
		Point pos = pj.toPixels(gp, null);

		// 求距离
		int distance = gp.distanceTo(center);
		
		mMapView.invalidate();
	}

	// 加入线段＋加icon,也可以用MapOverlay绘制
	public void onAddMapLayer(View v) {
		GeoPoint gp = (GeoPoint) mMapView.getMapCenter();
		mMarklist.add(gp);

		// 打点连线－－加入连续线段
		// mMapView.getOverlays().add(line);
		drawLine();

		// 打点 icon －－加入大量的icon,可点选。
		// mMapView.getOverlays().add(marker);
		addMarker(gp);
	}

	// 清除图层
	public void onClearMapLayer(View v) {
		mMarklist.clear();
		mMapView.getOverlays().clear();
		mMapView.invalidate();
	}

	public void onAddarea(View v) {
		final Projection pj = mMapView.getProjection();
		// left+top
		GeoPoint g0 = (GeoPoint) pj.fromPixels(50, 100, null);
		// right+bottom
		GeoPoint g1 = (GeoPoint) pj.fromPixels(300, 300, null);

		sCentralParkBoundingBox = new BoundingBoxE6(g0.getLatitude(),
				g1.getLongitude(), g1.getLatitude(), g0.getLongitude());

		mMapView.getOverlayManager().add(mMapOverlay);
		mMapView.invalidate();
	}

	public ArrayList<GeoPoint> mMarklist = new ArrayList<GeoPoint>();

	void drawLine() {
		PathOverlay line = new PathOverlay(Color.BLUE, this);
		for (GeoPoint gp : mMarklist) {
			line.addPoint(gp);
		}
		mMapView.getOverlays().add(line);
	}

	void addMarker(GeoPoint gp1) {
		if (gp1 == null)
			return;

		if (mResourceProxy == null) {
			mResourceProxy = new ResourceProxyImpl(getApplicationContext());
		}

		// 加入可以点选的icon
		ArrayList<OverlayItem> markers = new ArrayList<OverlayItem>();
		OverlayItem one = new OverlayItem("1", "marker1", gp1);
		Drawable drawable = getResources().getDrawable(R.drawable.map_marker);
		one.setMarker(drawable);
		markers.add(one);

		CustomMarker marker = new CustomMarker(markers,
				new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
					@Override
					public boolean onItemSingleTapUp(final int index,
							final OverlayItem item) {
						return true;
					}

					@Override
					public boolean onItemLongPress(final int index,
							final OverlayItem item) {
						return false;
					}
				}, mResourceProxy);
		mMapView.getOverlays().add(marker);
		mMapView.getController().setCenter(gp1);
		mMapView.invalidate();
	}

	// 定义图层上可点击的icon
	public class CustomMarker extends ItemizedOverlayWithFocus<OverlayItem>
			implements
			com.mapkit.views.overlay.ItemizedIconOverlay.OnItemGestureListener<OverlayItem> {
		public CustomMarker(List<OverlayItem> aList,
				OnItemGestureListener<OverlayItem> aOnItemTapListener,
				ResourceProxy pResourceProxy) {
			super(aList, aOnItemTapListener, pResourceProxy);
		}

		@Override
		public void addItem(int location, OverlayItem item) {
			super.addItem(location, item);
		}

		@Override
		protected boolean onTap(int index) {
			return super.onTap(index);
		}

		@Override
		public boolean onSingleTapUp(MotionEvent event, MapView mapView) {
			return super.onSingleTapUp(event, mapView);
		}

		@Override
		public int size() {
			return super.size();
		}

		@Override
		public boolean onItemLongPress(int arg0, OverlayItem arg1) {
			return true;
		}

		@Override
		public boolean onItemSingleTapUp(int arg0, OverlayItem arg1) {
			return true;
		}

	}

	private MapOverlay mMapOverlay;
	// 在图层mMapOverlay里使用，外部设置的需要绘制的矩形框
	private BoundingBoxE6 sCentralParkBoundingBox;

	// 车标经纬读
	GeoPoint _carll;
	// 车标的方向
	int _dir = 0;

	class MapOverlay extends Overlay {

		GeoPoint mTopLeft;
		GeoPoint mBottomRight;
		Point mTopLeftPoint = new Point();
		Point mBottomRightPoint = new Point();
		Point mCarPoint;

		public MapOverlay(Context ctx) {
			super(ctx);
		}

		@Override
		protected void draw(Canvas c, MapView osmv, boolean shadow) {
			// 屏幕中心点图钉
//			Bitmap bm = ((BitmapDrawable) getResources().getDrawable(
//					R.drawable.redpin)).getBitmap();
//			c.drawBitmap(bm, (osmv.getWidth() - bm.getWidth()) / 2,
//					(osmv.getHeight() - bm.getHeight()) / 2, new Paint());
			final Projection proj = osmv.getProjection();
			if (proj == null) {
				return;
			}
			
			// 画有方向的车标
			if (_carll != null) {
				mCarPoint = new Point();
				proj.toPixels(_carll, mCarPoint);
				drawCar(c);
			}
			
			if (sCentralParkBoundingBox == null) {
				return;
			}

			mTopLeft = new GeoPoint(sCentralParkBoundingBox.getLatNorthE6(),
					sCentralParkBoundingBox.getLonWestE6());
			mBottomRight = new GeoPoint(
					sCentralParkBoundingBox.getLatSouthE6(),
					sCentralParkBoundingBox.getLonEastE6());

			proj.toPixels(mTopLeft, mTopLeftPoint);
			proj.toPixels(mBottomRight, mBottomRightPoint);

			Rect area = new Rect(mTopLeftPoint.x, mTopLeftPoint.y,
					mBottomRightPoint.x, mBottomRightPoint.y);
			Paint p = new Paint();
			p.setColor(Color.argb(50, 255, 0, 0));
			c.drawRect(area, p);

			// 写文字
			p.setColor(0xFF0000FF);
			p.setTextSize(20);
			int y = (mTopLeftPoint.y + mBottomRightPoint.y) / 2;
			c.drawText("henry", mTopLeftPoint.x, y, p);

		
		}

		// 绘制车标，即有方向的icon
		private void drawCar(Canvas c) {
			if (mCarPoint.x < 0 || mCarPoint.y < 0) {
				return;
			}
			Bitmap bm;
			
/*			if (_splash <= 2) {
//				bm = ((BitmapDrawable) getResources().getDrawable(
//						R.drawable.car)).getBitmap();
				return;
			} else {
				bm = ((BitmapDrawable) getResources().getDrawable(
						R.drawable.i3_car00)).getBitmap();
				_splash = 0;
			}
*/			
			bm = ((BitmapDrawable) getResources().getDrawable(
					R.drawable.i3_car00)).getBitmap();
			
//			Bitmap rBm = rotateBitmap(bm, _dir);
//			c.drawBitmap(rBm, mCarPoint.x, mCarPoint.y, new Paint());
			c.drawBitmap(bm, mCarPoint.x, mCarPoint.y, new Paint());

		}
	}

	public static Bitmap rotateBitmap(Bitmap bitmap, int degree) {
		int width = bitmap.getWidth();
		int height = bitmap.getHeight();
		Matrix matrix = new Matrix();
		matrix.setRotate(degree);
		Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
				matrix, true);
		return newbmp;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			new AlertDialog.Builder(this)
					.setTitle(getString(R.string.dlg_title))
					.setMessage(getString(R.string.is_exit))
					.setPositiveButton(getString(R.string.yes),
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									finish();
									System.exit(0);
								}
							})
					.setNegativeButton(getString(R.string.cancel), null).show();
		}

		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == 600) {
			// 查询定位
			int pos = data.getIntExtra("poiIndex", 0);
			YSPOIData poiData = GeocodeService.getInstance().getPoiDatas()
					.get(pos);
			GeoPoint center = new GeoPoint(poiData.lat, poiData.lon);
			mMapView.getController().setCenter(center);
			mMapView.getController().setZoom(14);
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onCurrentLocation(Location location) {
		if (location == null) {
			return;
		}

		LonLatDouble ll = Wgtochina.getInstance().new LonLatDouble();
		ll.lon = location.getLongitude();
		ll.lat = location.getLatitude();
		Wgtochina.getInstance().wgtochina(ll);
		double lat = ll.lat;
		double lon = ll.lon;
		
//		GeoPoint center = new GeoPoint(lat, lon);
//		mMapView.getController().setCenter(center);
//		mMapView.getController().setZoom(14);
		_location = new GeoPoint(lat, lon);
		_carll = _location;
		
	}
	GeoPoint _location;
	
	public void onLocation(View v) {
		if (_location == null) {
			if (!NetLocationManager.getInstance().checkGPS()) {
				Toast.makeText(this, "需要开启GPS哟，否则无法定位!",
						Toast.LENGTH_SHORT).show();
				return;
			}
			Toast.makeText(this, "已开启GPS，但无有效定位!", Toast.LENGTH_SHORT).show();
		} else {
			mMapView.getController().setCenter(_location);
			//mMapView.getController().setZoom(14);
		}
	}
	
}
